package com.skyolder.milkbee.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.skyolder.milkbee.service.AwardService;
import com.skyolder.milkbee.web.rest.util.HeaderUtil;
import com.skyolder.milkbee.web.rest.util.PaginationUtil;
import com.skyolder.milkbee.web.util.WebUserUtil;
import com.skyolder.milkbee.service.dto.AwardDTO;

import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.ZonedDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * REST controller for managing Award.
 */
@RestController
@RequestMapping("/api")
public class AwardResource {

    private final Logger log = LoggerFactory.getLogger(AwardResource.class);
        
    @Inject
    private AwardService awardService;
    @Inject
	private WebUserUtil webUserUtil;

    /**
     * POST  /awards : Create a new award.
     *
     * @param awardDTO the awardDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new awardDTO, or with status 400 (Bad Request) if the award has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/awards")
    @Timed
    public ResponseEntity<AwardDTO> createAward(@RequestBody AwardDTO awardDTO) throws URISyntaxException {
        log.debug("REST request to save Award : {}", awardDTO);
        if (awardDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("award", "idexists", "A new award cannot already have an ID")).body(null);
        }
        awardDTO.setCreatedAt(ZonedDateTime.now());
        awardDTO.setLeaguerId(webUserUtil.getCurrentLeaguer().getId());
        awardDTO.setUserId(webUserUtil.getCurrentUser().getId());
        AwardDTO result = awardService.save(awardDTO);
        return ResponseEntity.created(new URI("/api/awards/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("award", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /awards : Updates an existing award.
     *
     * @param awardDTO the awardDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated awardDTO,
     * or with status 400 (Bad Request) if the awardDTO is not valid,
     * or with status 500 (Internal Server Error) if the awardDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/awards")
    @Timed
    public ResponseEntity<AwardDTO> updateAward(@RequestBody AwardDTO awardDTO) throws URISyntaxException {
        log.debug("REST request to update Award : {}", awardDTO);
        if (awardDTO.getId() == null) {
            return createAward(awardDTO);
        }
        AwardDTO result = awardService.save(awardDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("award", awardDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /awards : get all the awards.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of awards in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @GetMapping("/awards")
    @Timed
    public ResponseEntity<List<AwardDTO>> getAllAwards(@ApiParam Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of Awards");
        Page<AwardDTO> page = awardService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/awards");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /awards/:id : get the "id" award.
     *
     * @param id the id of the awardDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the awardDTO, or with status 404 (Not Found)
     */
    @GetMapping("/awards/{id}")
    @Timed
    public ResponseEntity<AwardDTO> getAward(@PathVariable Long id) {
        log.debug("REST request to get Award : {}", id);
        AwardDTO awardDTO = awardService.findOne(id);
        return Optional.ofNullable(awardDTO)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /awards/:id : delete the "id" award.
     *
     * @param id the id of the awardDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/awards/{id}")
    @Timed
    public ResponseEntity<Void> deleteAward(@PathVariable Long id) {
        log.debug("REST request to delete Award : {}", id);
        awardService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("award", id.toString())).build();
    }

}
